# -*- coding: utf-8 -*-
import datetime

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog, QMessageBox

from compoments.immediatelyFillDialog import Ui_Dialog
from service.workHourService import WorkHourService
from util import configJsonUtil
from util.loggerFactory import Logger

logger = Logger()


class ImmediatelyFillDialogImpl(QDialog, Ui_Dialog):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent
        self.setupUi(self)
        self.show()

        self.on_program_changed()
        self.parent.program_changed_signal.connect(self.on_program_changed)
        self.comboBox.currentTextChanged.connect(self.on_change)
        self.pushButton.clicked.connect(self.submit)
        self.pushButton_2.clicked.connect(self.close)
        # self.dateEdit_fill_day.setDate(QDate.currentDate())
        self.dateEdit_fill_day.setDate(datetime.date.today())
        self.cur_program_id = self.comboBox.currentText().split('_')[0]
        self.workHourService = WorkHourService()

    def format(self, p):
        title = '{}_{}_{}_{}_{}'.format(p['id'], p['xmmc'], p['xmbh'], p['rwmc'], p['rwbh'])
        return title

    def on_change(self, title):
        self.cur_program_id = title.split('-')[0]

    def on_program_changed(self):
        self.comboBox.clear()
        config = configJsonUtil.get_config()
        self.account = config['account']
        self.programs = config['programs']
        self.formater = list(map(self.format, self.programs))
        self.comboBox.addItems(self.formater)

    def submit(self):
        try:
            pr = [p for p in self.programs if str(p['id']) == self.cur_program_id][0]
            work_hour = {
                "xmbh": pr['xmbh'],
                "xmmc": pr['xmmc'],
                "rwbh": pr['rwbh'],
                "rwmc": pr['rwmc'],
                "gs": str(pr['gs']),
                "nr": pr['nr'],
                "fid": '',
                "shzt": '0'
            }
            day = self.dateEdit_fill_day.date().toString(Qt.ISODate)
            ret = self.workHourService.fill_work_hour(day=day, work_hour_dict=work_hour)
            message_ = ret['message'] if ret['message'] != '' else '成功'
            logger.info("submit work_hour ret:" + message_)
            QMessageBox.information(self, "提示", "工时填报结果：" + message_, QMessageBox.Yes, QMessageBox.Yes)
        except Exception as e:
            logger.error(e)
            QMessageBox.warning(self, "错误", "{}".format(e), QMessageBox.Yes, QMessageBox.Yes)
